package common.store.admin.contoller;

import common.store.admin.dto.Product;
import common.store.admin.service.AdminOrderService;
import common.store.admin.service.AdminProductService;
import common.store.admin.service.impl.AdminOrderServiceImpl;
import common.store.admin.service.impl.AdminProductServiceImpl;
import common.store.admin.vo.QueryVo;
import common.store.web.bean.Order;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/adminOrderList")
public class AdminOrderListServlet extends HttpServlet {

    private AdminOrderService adminOrderService;

    private AdminProductService adminProductService;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        adminProductService = new AdminProductServiceImpl();
        adminOrderService = new AdminOrderServiceImpl();

        String oid = req.getParameter("oid");
        List<Order> orders;
        if (oid == null || oid.equals("")){
            orders = adminOrderService.getOrderList();
            getOrderPrice(orders);
        }else {
            orders = adminOrderService.getOrderByOid(oid);
            getOrderPrice(orders);
        }

        req.setAttribute("orderList",orders);


        req.getRequestDispatcher("/admin/order/list.jsp").forward(req , resp);

    }

    private void getOrderPrice(List<Order> orders) {
        for (Order order :
                orders) {
            Product product = adminProductService.getProductByPid(order.getPid().toString());
            Double marketPrice = product.getMarketPrice();
            BigDecimal mp = BigDecimal.valueOf(marketPrice);
            BigDecimal count = BigDecimal.valueOf(order.getCount());
            order.setPrice(mp.multiply(count));
            System.out.println(order.getPrice());
        }
    }
}
